package com.youyi.yyscreencutlibrary.Core;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.IBinder;
import com.youyi.yyscreencutlibrary.Core.YYScreenShotHelper;
import org.greenrobot.eventbus.EventBus;

public class CaptureScreenService extends Service {
    private boolean hasSetBackBitmap;
    private YYScreenShotHelper mScreenShotHelper;

    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        createNotificationChannel();
        EventBus.getDefault().post(new StartScreenCutBean(true));
        return super.onStartCommand(intent, i, i2);
    }

    private void createNotificationChannel() {
        PendingIntent pendingIntent;
        Notification.Builder builder = new Notification.Builder(getApplicationContext());
        Intent intent = new Intent("com.youyi.yyscreencutlibrary.Core.CaptureScreenService");
        if (Build.VERSION.SDK_INT >= 31) {
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 201326592);
        } else {
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 1073741824);
        }
        builder.setContentIntent(pendingIntent).setContentText("正在截图").setWhen(System.currentTimeMillis());
        if (Build.VERSION.SDK_INT >= 26) {
            builder.setChannelId("notification_id");
        }
        if (Build.VERSION.SDK_INT >= 26) {
            ((NotificationManager) getSystemService("notification")).createNotificationChannel(new NotificationChannel("notification_id", "notification_name", 2));
        }
        Notification build = builder.build();
        build.defaults = 1;
        startForeground(110, build);
    }

    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }

    private void cutMethod(int i, Intent intent) {
        this.hasSetBackBitmap = false;
        YYScreenShotHelper yYScreenShotHelper = new YYScreenShotHelper(getApplicationContext(), i, intent, new YYScreenShotHelper.OnScreenShotListener() {

            @Override
            public void onFinish(Bitmap bitmap) {
                if (!CaptureScreenService.this.hasSetBackBitmap) {
                    CaptureScreenService.this.hasSetBackBitmap = true;
                    EventBus.getDefault().post(new CutBitmap(bitmap));
                }
            }
        });
        this.mScreenShotHelper = yYScreenShotHelper;
        yYScreenShotHelper.startScreenShot();
    }
}
